#coding:utf-8
# 面向对象方法写程序
import socket
import re

from mysqlClass import MysqlHelper
from multiprocessing import Process
# 设置静态文件根目录
HTML_ROOT_DIR = "./"


class WebServer(object):
    """WebServer类"""
    def __init__(self):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    def start(self):
        self.server_socket.listen(128)
        while True:
            client_socket, client_address = self.server_socket.accept()
            print("[%s, %s]用户链接上了" % client_address)
            # 创建子进程处理客户端
            handle_client_process = Process(target=self.handle_client, args=(client_socket,))
            handle_client_process.start()
            # 把当前主进程使用的socket关闭
            client_socket.close()

    def caibao(self,tuple_file):
        data_file = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>查询系统</title></head><body>"""
        for i in range(0,27):
            data_file += str(tuple_file[i])+"<br>"
        data_file += """</body></html>"""
        return data_file

    def connction_mysql(self, user, pwd):
        mysql = MysqlHelper("123.207.38.118", "python", "python", "python")
        try:
            # 查询语句
            sql = "select * from graduate where 学号=%s"
            result = mysql.inquire(sql, user)
            if len(result) == 0:
                return "学号不存在！"
            elif "2014040123" == user:
                return "<h1>儿子不要查爸爸的资料！</h1>"
            elif (pwd == "666666")or(result[0][4][12:] == pwd):
                return self.caibao(result[0])
            else:
                return "密码错误！"
        except Exception as sss:
            print("错误信息：%s" % sss)

    def handle_client(self,client_socket):
        """处理客户端请求"""
        # 获取客户端数据
        request_data = client_socket.recv(1024)
        # print("request data:", request_data)

        # 获取请求数据路径
        request_lines = request_data.splitlines()
        print("下面打印请求路径")
        for line in request_lines:
            print(line)
        try:
            request_line_1 = request_lines[0].decode("utf-8").split(" ", 3)
            # 获取请求方式
            request_mode = request_line_1[0]
            request_path = request_line_1[1]
        except Exception as result:
            print(result)

        # 解析请求报文
        # "GET / HTTP/1.1"
        # GET 请求处理
        if "GET" == request_mode:
            print("GET")
            # 提取用户请求的文件名
            file_name = request_path
            # print("测试：%s 路径：%s" % (file_name, request_path))
            if "/" == file_name:
                file_name = "/index.html"
            # 打开文件,读取内容
            try:
                file = open(HTML_ROOT_DIR + file_name, "rb")
            except IOError:
                response_start_line = "HTTP/1.1 404 Not Found\r\n"
                response_headers = "Server:My server\r\n"
                response_body = "The file is not found!"
            else:
                file_data = file.read()
                file.close()

                # 构造响应数据
                response_start_line = "HTTP/1.1 200 OK\r\n"
                response_headers = "Server:My server\r\n"
                response_body = file_data.decode("utf_8")
        # POST 请求处理
        elif "POST" == request_mode:
            request_file = request_lines[12].decode("utf-8")
            print("POST文件:%s" % request_file)
            user_name = re.search(r"user=\d*\b",request_file).group()
            password = re.search(r"pwd=\d*\b", request_file).group()

            sql_data = self.connction_mysql(user_name[5:],password[4:])
            # 构造响应数据
            response_start_line = "HTTP/1.1 200 OK\r\n"
            response_headers = "Server:My server\r\n"
            response_body = sql_data

        response = response_start_line + response_headers + "\r\n" + response_body
        # print("response data:", response)

        # 向客户端返回响应数据
        client_socket.send(bytes(response, "utf-8"))
        # 关闭客户端连接
        client_socket.close()

    def bind(self, address, port):
        self.server_socket.bind((address, port))


def main():
    http_server = WebServer()
    http_server.bind("", 8080)
    http_server.start()


if __name__ == "__main__":
    main()
